package com.demo.jdk.lambda;

import com.alibaba.fastjson.JSON;
import com.demo.model.Person;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;

@Slf4j
public class LambdaFunction {

    /**
     * 排序
     */
    public void sort() {

        List<Person> list = getPresons();
        log.info("LambdaFunction.sort 排序前 age:{}", JSON.toJSONString(list));
        list.sort(comparing("asc", Person::getAge));
        log.info("LambdaFunction.sort 排序后 age:{}", JSON.toJSONString(list));

        list = getPresons();
        log.info("LambdaFunction.sort 排序前 name:{}", JSON.toJSONString(list));
        list.sort(comparing("desc", Person::getName));
        log.info("LambdaFunction.sort 排序后 name:{}", JSON.toJSONString(list));
    }

    private List<Person> getPresons() {
        List<Person> list = new ArrayList<>();

        Person person = new Person();
        person.setName("aa");
        person.setAge(66);
        list.add(person);

        person = new Person();
        person.setName("aa");
        person.setAge(67);
        list.add(person);

        person = new Person();
        person.setName("bb");
        person.setAge(64);
        list.add(person);
        return list;
    }

    private <T, U extends Comparable<? super U>>Comparator<T> comparing(String isAsc, Function<T, U> keyExtractor) {
        if (StringUtils.equals(isAsc, "asc")) {
            return Comparator.comparing(keyExtractor);
        } else {
            return Comparator.comparing(keyExtractor).reversed();
        }
    }
}
